import Modeler from 'bpmn-js/lib/Modeler'
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import { contextMenuEventBus } from '../../utils/contextMenu'
import EventEmitter from '@/utils/EventEmitter'
export const initModeler = async (canvasRef, options, emit) => {
  const modelerStore = useModelerStore()
  modelerStore.$patch({
    scale: 1
  })
  options.container = canvasRef.value
  if (modelerStore.getModeler) {
    modelerStore.getModeler.destroy()
    await modelerStore.setModeler(null)
  }
  const modeler = new Modeler(options)
  await modelerStore.setModeler(markRaw(modeler))
  EventEmitter.emit('modeler-init', modeler)
  contextMenuEventBus(modeler)
  modeler.on('commandStack.changed', async (event) => {
    try {
      const { xml } = await modeler.saveXML({ format: true })
      modelerStore.xml = xml
      emit('command-stack-changed', event)
    } catch (error) {
      console.error(error)
    }
  })
}
